package com.realshare.bby.service.integral;

import com.realshare.frame.util.DateUtils;
import com.realshare.frame.util.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 过期积分清空
 *
 * @author Administrator
 */
@Service
public class IntegralClear {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SQLManager sqlManager;

    /**
     * 每年1月1号凌晨执行清理过期积分
     * 根据积分有效期（默认2年，可设置）进行清理积分
     */
    public void clear() {
        log.debug("开始清理积分");
        try {
            String now = DateUtils.getNowDateTime();
            Map<String, String> param = new HashMap<String, String>();
            param.put("now", now);
            //查询积分的有效月份
            int integralEffectiveLimit = sqlManager.intValue("integral.calculate.findNeedClear", param);
            if (integralEffectiveLimit <= 0) {
                return;
            }
            log.info("发现满足清理积分条件，开始清理积分");
            String clearDate = DateUtils.format(DateUtils.addMonth(new Date(), -integralEffectiveLimit), "yyyyMMdd");
            //查询上次清理积分的时间
            String lastClearTime = sqlManager.selectSingle("integral.calculate.findLastClearTime", now, String.class);

            lastClearTime = StringUtils.isNotBlank(lastClearTime) ? lastClearTime : "1970-01-01";
            String tableName = "customer_means_sys_" + DateUtils.getNow("yyMMdd");
            param.put("TableSchema", sqlManager.getDs().getMetaData().getCatalog());
            param.put("tableName", tableName);
            int count = sqlManager.intValue("integral.calculate.findContainTable", param);

            if (count > 0) {
                sqlManager.executeUpdate(new SQLReady("drop table " + tableName));
            }
            String sql = "create table " + tableName + " as select * from customer_means";
            sqlManager.executeUpdate(new SQLReady(sql));

            param.put("clearDate", clearDate);
            param.put("lastClearTime", lastClearTime);
            //插入需要清理积分的日志记录，状态为未清理积分
            sqlManager.update("integral.calculate.insertClearLog", param);

            //根据日志记录清理积分
            sqlManager.update("integral.calculate.clearIntegralByLog");

            //更新日志记录状态为已清理积分
            sql = "update jf_integral_clear_log set status='1' where status='0'";
            sqlManager.executeUpdate(new SQLReady(sql));
        } catch (Exception e) {
            e.printStackTrace();
            log.info("清理积分时出错，错误信息为：" + e.getMessage());
        }
        log.info("结束清理积分");
    }

}
